import time
import subprocess
from gravityassist.musiclib import get_music_list
from gravityassist.config import get_option

last_play_time = 0
current_queue = []

def play_music(id: int):
    curr_play_time = time.time()
    queued = curr_play_time - last_play_time <= 5
    musics = get_music_list()
    if id < 0 or id >= len(musics):
        return {'playing': False, 'message': 'Music id out of range, please use list_music to get accuerate music id first'}
    music = musics[id]
    music_path = music["path"]
    # if not queued:
    #     current_queue.clear()
    # current_queue.append(music_path)
    #rest_musics = [music["path"] for music in musics]
    #random.shuffle(rest_musics)
    # try:
    #     command = ['cvlc', '--one-instance', '--', 'vlc://quit']
    #     subprocess.check_call(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    # except:
    #     traceback.print_exc()
    # command = ['vlc', '--one-instance', '--no-random', '--no-loop', '--'] + current_queue + rest_musics
    command = ['vlc', '--one-instance', '--no-random', '--no-loop']
    if get_option('music_quiet'):
        command += ['--no-video']
    if queued:
        command.append('--playlist-enqueue')
    command.append('--')
    command.append(music_path)
    subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return {'playing': True, 'name': music["name"]}
